<template>
  <div style="position: relative">
    <div ref="echartDom" v-bind="$attrs"></div>
    <div class="check-time-year-or-month" :style="{...magnifyFontSizeObj}">
      <el-button :class="housingSupplyStatsData?.xAxisTimeType === 'year' ? 'active-btn' : ''" @click.stop="changeXAxisTimeTypeFunc('year')">按年</el-button>
      <el-button :class="housingSupplyStatsData?.xAxisTimeType === 'month' ? 'active-btn' : ''" @click.stop="changeXAxisTimeTypeFunc('month')">按月</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {inject, ref, reactive, shallowRef, onMounted, onUnmounted, watchEffect, defineEmits, defineExpose} from "vue";
import { pxToRem } from "@/utils/index";

// 接收参数
const props = defineProps({
  housingSupplyStatsData: {
    type: Object,
    default: () => {},
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});
// 数据定义
const chartsData = reactive<any>({
  legendData: [],
  xAxisData: [],
  yAxisData: [],
  seriesData: [],
});
const echartDom = ref<null | HTMLDivElement>(null);
const myChart = shallowRef<null | any>(null);
const echarts = inject<any>("echarts");

// echarts初始化渲染
chartsData.legendData = props.housingSupplyStatsData.legendData;
chartsData.xAxisData = props.housingSupplyStatsData.xAxisData;
chartsData.yAxisData = props.housingSupplyStatsData.yAxisData;
chartsData.seriesData = props.housingSupplyStatsData.seriesData;
const colors = props.housingSupplyStatsData.colors;
const typeData = props.housingSupplyStatsData.typeData;
const legendSty = props.housingSupplyStatsData.legendStyle;
const gridSty = props.housingSupplyStatsData.gridConfig;

const emit = defineEmits(['changeXAxisTimeType', 'dialogEmit'])

const magnifyFontSizeObj = ref({
  '--custom-font-size-0-or-minus-5': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? -5 : 0) + 'px',
  '--custom-font-size-10': pxToRem(props?.dialogData?.fontSizeTimes * 10) + 'px',
  '--custom-font-size-20': pxToRem(props?.dialogData?.fontSizeTimes * 20) + 'px',
  '--custom-font-size-20-30': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 20 : 60) + 'px',
})

const getEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    // 图例配置
    const legendStyle = {
      show: legendSty.show,
      icon: legendSty.icon,
      left: legendSty.right ? "auto" : pxToRem(legendSty.left),
      right: pxToRem(legendSty.right),
      top: pxToRem(legendSty.top),
      itemWidth: pxToRem(legendSty.itemWidth * props?.dialogData?.fontSizeTimes),
      itemHeight: pxToRem(legendSty.itemHeight * props?.dialogData?.fontSizeTimes),
      itemGap: pxToRem(legendSty.itemGap * props?.dialogData?.fontSizeTimes),
      textStyle: {
        color: "#fff",
        fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        rich: {},
        padding: [0, 0, pxToRem(-3), 0],
      },
      data: chartsData.legendData,
    };

    // 网格区域
    const gridConfig = {
      left: gridSty.left,
      right: props?.dialogData?.fontSizeTimes === 1 ? gridSty.right : '7%',
      bottom: gridSty.bottom,
      top: gridSty.top,
      containLabel: true,
    };

    // x轴配置
    const xAxisConfig = {
      boundaryGap: true,
      data: chartsData.xAxisData,
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          color: "#FFFFFF",
          fontSize: pxToRem(12),
        },
      },
      
    };

    // y轴配置
    const yAxisConfig = chartsData.yAxisData.map((item: any) => ({
      type: "value",
      name: item.name,
      nameTextStyle: {
        color: "#959699",
        fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
      },
      nameGap: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 15 : 25),
      splitLine: {
        show: item.type == 2 ? false : true,
        lineStyle: {
          color: "#31679C",
          type: "dashed",
        },
      },
      axisLabel: {
        formatter: "{value}",
        color: "#959699",
        fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
      },
    }));

    const tempTooltipDom = (params: any) => {
      let tempDom: string = ''
      if (params?.length === 3) {
        tempDom = (
            params?.[0]?.axisValue + '<br>' +
            `${params?.[0]?.name} ` + `同比：${params[0].data?.yoyPercentage}%` + (props?.housingSupplyStatsData?.xAxisTimeType === 'month' ? ` 环比：${params[0].data?.momPercentage}%` : '') + '<br>' +
            `${params?.[1]?.name} ` + `同比：${params[1].data?.yoyPercentage}%` + (props?.housingSupplyStatsData?.xAxisTimeType === 'month' ? ` 环比：${params[1].data?.momPercentage}%` : '') + '<br>' +
            `${params?.[2]?.name} ` + `同比：${params[2].data?.yoyPercentage}%` + (props?.housingSupplyStatsData?.xAxisTimeType === 'month' ? ` 环比：${params[2].data?.momPercentage}%` : '')
        )
      } else {
        tempDom = (
            params?.[0]?.axisValue + '<br>' +
            `${params?.[0]?.name} ` + `同比：${params[0].data?.yoyPercentage}%` + (props?.housingSupplyStatsData?.xAxisTimeType === 'month' ? ` 环比：${params[0].data?.momPercentage}%` : '') + '<br>' +
            `${params?.[1]?.name} ` + `同比：${params[1].data?.yoyPercentage}%` + (props?.housingSupplyStatsData?.xAxisTimeType === 'month' ? ` 环比：${params[1].data?.momPercentage}%` : '')
        )
      }
      return tempDom
    }

    // 数据项配置
    const seriesConfig = chartsData.seriesData.map((data: any, index: string | number) => ({
      name: chartsData.legendData[index],
      type: typeData[index].name,
      barWidth: '28%', // 设置为类目宽度的50%
      data: data,
      symbol: "none",
      smooth: true,
      stack: typeData[index].stack == 2 ? "account" : null,
      yAxisIndex: typeData[index].type == 2 ? 1 : 0,
      areaStyle:
        typeData[index].areaStyleType == 2
          ? {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: colors[index].a, // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: colors[index].b, // 100% 处的颜色
                  },
                ],
              },
            }
          : null,
      itemStyle: {
        color: {
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          type: "linear",
          global: false,
          colorStops: [
            {
              offset: 0,
              color: colors[index].a,
            },
            {
              offset: 1,
              color: colors[index].b,
            },
          ],
        },
      },
    }));
    // 渲染图表数据
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: function (params: any) {
          return tempTooltipDom(params)
        }
      },
      dataZoom: { // 数据过多内部拖动逻辑
        type: "slider",
        startValue: 0,
        endValue: 10,
        height: pxToRem(20),
        bottom: pxToRem(10)
      },
      legend: legendStyle,
      grid: gridConfig,
      xAxis: xAxisConfig,
      yAxis: yAxisConfig,
      series: seriesConfig,
    };
    myChart.value.setOption(option);

    myChart.value.on('legendselectChanged', (params: any) =>{
      event.stopPropagation();
    })
  }
};

const changeFontSize = () => { // 动态改变字体大小方法
  magnifyFontSizeObj.value = {
    '--custom-font-size-0-or-minus-5': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 0 : 0) + 'px',
    '--custom-font-size-10': pxToRem(props?.dialogData?.fontSizeTimes * 10) + 'px',
    '--custom-font-size-20': pxToRem(props?.dialogData?.fontSizeTimes * 20) + 'px',
    '--custom-font-size-20-30': pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 20 : 60) + 'px',
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  chartsData.legendData = props.housingSupplyStatsData.legendData;
  chartsData.xAxisData = props.housingSupplyStatsData.xAxisData;
  chartsData.yAxisData = props.housingSupplyStatsData.yAxisData;
  chartsData.seriesData = props.housingSupplyStatsData.seriesData;
  changeFontSize();
  getEchart();
};

const changeXAxisTimeTypeFunc = (val: any) => {
  emit('changeXAxisTimeType', val)
  emit('dialogEmit', {type: props?.housingSupplyStatsData?.moduleName, value: val})
}

watchEffect(() => {
  updateChart();
});

defineExpose({
  updateChart
})

onMounted(() => {
  getEchart();
  window.addEventListener("resize", updateChart);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
});
</script>
<style scoped lang="less">
.h200 {
  height: 200px;
}
.dialog-h200 {
  width: 1120px;
  height: 500px;
}
.check-time-year-or-month {
  position: absolute;
  right: var(--custom-font-size-0-or-minus-5);
  bottom: 30%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .el-button {
    width: var(--custom-font-size-20-30);
    height: var(--custom-font-size-20);
    margin: 0;
    font-size: var(--custom-font-size-10);
    box-shadow: inset 0 0 0.04167rem 0 #3D7FFF;
    border-radius: 0.04167rem;
    cursor: pointer;
    color: white;
    background-color: transparent;
    border: 0;
  }
  .el-button:last-child {
    margin-top: 5px;
  }
  .el-button.active-btn {
    background: linear-gradient(60deg, #0E5FFF 0%, #00FFFF 100%);
  }
}
</style>
